package com.stu.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author MI
 * @ClassName XmlUtils.java
 * @createTime 2021年11月15日 22:37:00
 */
@Slf4j
public class XmlUtils {
    public static XmlMapper xmlMapper = new XmlMapper();

    static {
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        xmlMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
        xmlMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        // xmlMapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
        xmlMapper.enable(MapperFeature.USE_STD_BEAN_NAMING);
        //序列化加上头部信息 <就是那个xml 头部 <?xml version='1.0' encoding='UTF-8'?>>
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
        xmlMapper.setDefaultUseWrapper(false);
        //美化输出
        xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
    }

    public static String jacksonBean2XML(Object value) {
        try {
            return xmlMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            log.error("实体转xml失败", e);
        }
        return null;
    }

    public static <T> T jacksonXML2Bean(String xmlStr, Class<T> clazz) {
        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.setDefaultUseWrapper(false);
        //自动忽略无法对应pojo的字段
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            return xmlMapper.readValue(xmlStr, clazz);
        } catch (IOException e) {
            log.error("xml字符串转实体失败", e);
        }
        return null;
    }
}
